package YAVMM::GuestDB::Plugin::SQLite;
use Moose::Role;

use DBI;

use YAVMM::Guest;
use YAVMM::Error::DBError;

has '_dbh' => (
    is         => 'rw',
    lazy_build => 1,
);

sub get_guest {
    my $self = shift;
    my $name = shift;

    my $sql = 'select name, host, data from guests where name = ?';
    my $sth = $self->_dbi->prepare($sql)
	or die YAVMM::Error::DBError->new(
	    error => "Can't get guest: ".$self->_dbi->errstr
	);

    $sth->execute($name)
	or die YAVMM::Error::DBError->new(
	    error => "Can't get guest: ".$self->_dbi->errstr
	);

    my $result = $sth->fetchrow_hashref;
    return undef if not defined $result;

    my $guest;
    try {
	$guest = YAVMM::Guest->thaw($result->{data});
    } catch ($err) {
	die YAVMM::Error::DBError->error(
	    error => 'Unable to read guest data'
	);
    }

    return $guest;
}

sub set_status {
    my $self   = shift;
    my $guest  = shift;
    my $status = shift;

    my $sql = 'update guests set data = ? where name = ?';
    my $sth = $self->_dbi->prepare($sql)
	or die YAVMM::Error::DBError->new(
	    error => "Can't get guest: ".$self->_dbi->errstr
	);

    $sth->execute($guest->freeze, $name)
	or die YAVMM::Error::DBError->new(
	    error => "Can't get guest: ".$self->_dbi->errstr
	);

    return $guest;
}

sub _build__dbh {
    my $self = shift;

    # TODO: need a reasonable default
    my $dbfile = $self->settings->get('guest sqlite', 'file');

    my $dbh = DBI->connect_cached("dbi:SQLite:dbname=$dbfile", "", "");
    if (not $dbh) {
	die YAVMM::Error::DBError->new(
	    error => "Can't connect to database: ".DBI->errstr
	);
    }

    return $dbh;
}

1;

__END__
